<script setup lang="ts">
import { ref, watch, computed } from 'vue'
import type { CheckboxValueType } from 'element-plus'

const props = defineProps({
  modelValue: {
    type: Array,
    default: () => [],
  },
  options: {
    type: Array,
    default: () => [],
  },
})

const emits = defineEmits(['update:modelValue', 'change'])

const innerValue = computed({
  get: () => props.modelValue,
  set: (newValue) => {
    emits('update:modelValue', newValue)
  },
})

const checkType = ref('') // 只能选择一个类型

const checkOptions = computed(() => {
  if (!checkType.value) {
    checkType.value = props.options[0].value
  }
  if (checkType.value) {
    return props.options.filter((_) => _.value === checkType.value)[0].children
  }
})

const checkTypeChange = () => {
  // checkAll.value = false
  // indeterminate.value = false
  innerValue.value = []
}

// checkbox 逻辑
const checkAll = ref(false)
const indeterminate = ref(false)

watch(innerValue, (val) => {
  if (val.length === 0) {
    checkAll.value = false
    indeterminate.value = false
  } else if (val.length === checkOptions.value.length) {
    checkAll.value = true
    indeterminate.value = false
  } else {
    indeterminate.value = true
  }
})

const handleCheckAll = (val: CheckboxValueType) => {
  indeterminate.value = false
  if (val) {
    innerValue.value = checkOptions.value.map((_) => _.value)
  } else {
    innerValue.value = []
  }
}

const handleCheckedChange = (value: CheckboxValueType[]) => {
  emits('change', value)
}

// TODO select 逻辑多选，绑定Item
</script>

<template>
  <el-popover
    placement="bottom"
    :width="560"
    trigger="click"
  >
    <template #reference>
      <el-input-tag v-model="innerValue" clearable></el-input-tag>
    </template>
    <div class="container-main">
      <el-radio-group v-model="checkType" @change="checkTypeChange">
        <el-radio-button v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
      </el-radio-group>

      <div class="check-all">
        <el-checkbox v-model="checkAll" :indeterminate="indeterminate" @change="handleCheckAll">
          All
        </el-checkbox>
      </div>
      <div style="padding-left: 24px">
        <el-checkbox-group v-model="innerValue" @change="handleCheckedChange">
            <el-checkbox v-for="item in checkOptions" :key="item.id" :label="item.value">
              {{ item.value }}
            </el-checkbox>
        </el-checkbox-group>
      </div>
    </div>
  </el-popover>
</template>

<style scoped lang="scss">
.container-main{
  padding: 5px;
  .check-all{
    margin-top: 12px;
  }
}
</style>
